import { checkLoginStatus, showMessage, formatPrice, formatTime } from './common.js';
import api from "./api";

// 全局状态管理
const state = {
    currentPage: 1,
    pageSize: 10,
    totalProducts: 0,
    currentView: 'grid',
    isLoading: false,
    activeFilters: {}
};

// DOM 引用缓存
const dom = {
    productsView: document.getElementById('products-view'),
    resultCount: document.getElementById('result-count'),
    prevPageBtn: document.getElementById('prev-page'),
    nextPageBtn: document.getElementById('next-page'),
    pageNumbers: document.querySelector('.page-numbers'),
    categoryFilter: document.getElementById('category-filter'),
    sortBy: document.getElementById('sort-by'),
    minPrice: document.getElementById('min-price'),
    maxPrice: document.getElementById('max-price'),
    viewBtns: document.querySelectorAll('.view-btn')
};

// 显示加载状态
function showLoading() {
    if (dom.productsView) {
        dom.productsView.innerHTML = '<div class="loading-container"><div class="loading-spinner"></div></div>';
        state.isLoading = true;
    }
}

// 隐藏加载状态
function hideLoading() {
    state.isLoading = false;
    if (dom.productsView && dom.productsView.classList.contains('loading-container')) {
        dom.productsView.innerHTML = '';
    }
}

// 加载商品列表
async function loadProducts(page = state.currentPage, filters = {}) {
    if (state.isLoading) return;

    showLoading();

    try {
        // 合并筛选条件
        state.activeFilters = { ...state.activeFilters, ...filters };

        const response = await api.products.getByPage(
            page,
            state.pageSize,
            state.activeFilters,
            alert(response.data.products.length),
            state.currentView === 'list' ? 1 : 2,
            alert(response.data.products)
        );

        if (response.success) {
            state.totalProducts = response.data.total;
            state.currentPage = page;
            renderProducts(response.data.products);
            renderPagination();
            updateResultCount();
        }
    } catch (error) {
        showMessage('error', '加载商品失败');
        console.error('商品加载错误:', error);
    } finally {
        hideLoading();
    }
}

// 渲染商品列表
function renderProducts(products) {
    if (!dom.productsView) return;

    dom.productsView.innerHTML = '';

    if (products.length === 0) {
        dom.productsView.innerHTML = '<div class="no-products">暂无商品</div>';
        return;
    }

    products.forEach(product => {
        const productCard = createProductCard(product);
        dom.productsView.appendChild(productCard);
    });

    setupProductEvents();
}

// 创建商品卡片
function createProductCard(product) {
    const productCard = document.createElement('div');
    productCard.className = `product-card transition-all duration-300 ${state.currentView === 'list' ? 'list-view' : 'grid-view'}`;
    productCard.dataset.id = product.id;

    productCard.innerHTML = `
        <div class="product-image relative">
            <img src="${getProductImage(product)}" alt="${product.name}" class="w-full h-48 object-cover">
            ${getProductStatusBadge(product)}
        </div>
        <div class="product-info p-3">
            <h3 class="product-name mb-1">
                <a href="product-detail.html?id=${product.id}" class="text-dark hover:text-primary transition-colors">
                    ${product.name}
                </a>
            </h3>
            <div class="product-price font-bold text-primary mb-2">${formatPrice(product.price)}</div>
            <div class="product-meta text-sm text-gray-500 mb-3">
                <span class="mr-3"><i class="fas fa-map-marker-alt mr-1"></i> ${product.location || '未知地点'}</span>
                <span><i class="fas fa-clock mr-1"></i> ${formatTime(product.tags)}</span>
            </div>
            <div class="product-actions flex space-x-2">
                <button class="btn-add-cart flex-1 py-1.5 border border-gray-300 rounded-md text-sm" data-id="${product.id}">
                    <i class="fas fa-cart-plus mr-1"></i> 加入购物车
                </button>
                <button class="btn-favorite flex-1 py-1.5 border border-gray-300 rounded-md text-sm" data-id="${product.id}">
                    <i class="fas fa-heart ${product.tags? 'text-red-500' : ''}"></i> 收藏
                </button>
            </div>
        </div>
    `;

    return productCard;
}

// 获取商品图片
function getProductImage(product) {
    return product.images && product.images.length > 0
        ? `/uploads/products/${product.images[0]}`
        : 'default-product.jpg';
}

// 获取商品状态标签
function getProductStatusBadge(product) {
    if (product.status === 1) {
        return '<span class="status-badge absolute top-2 right-2 bg-green-100 text-green-800 text-xs py-1 px-2 rounded">全新</span>';
    }
    return '';
}

// 设置商品卡片事件
function setupProductEvents() {
    // 加入购物车事件委托
    dom.productsView.addEventListener('click', (e) => {
        const addToCartBtn = e.target.closest('.btn-add-cart');
        if (addToCartBtn) {
            addToCart(addToCartBtn.dataset.id);
        }
    });

    // 收藏事件委托
    dom.productsView.addEventListener('click', (e) => {
        const favoriteBtn = e.target.closest('.btn-favorite');
        if (favoriteBtn) {
            addToFavorite(favoriteBtn.dataset.id);
        }
    });
}

// 添加购物车
async function addToCart(productId) {
    const user = await checkLoginStatus();
    if (!user) {
        showMessage('warning', '请先登录');
        window.location.href = 'login.html';
        return;
    }

    try {
        const response = await api.shoppingCart.add({
            productId,
            quantity: 1,
            userId: user.id
        });

        if (response.success) {
            showMessage('success', '已加入购物车');
            // 触发购物车数量更新事件
            document.dispatchEvent(new Event('cartCountUpdated'));
        }
    } catch (error) {
        showMessage('error', error.message || '加入购物车失败');
    }
}

// 添加收藏
async function addToFavorite(productId) {
    const user = await checkLoginStatus();
    if (!user) {
        showMessage('warning', '请先登录');
        window.location.href = 'login.html';
        return;
    }

    try {
        const isFavorite = await api.products.isFavorite(productId);

        if (isFavorite) {
            await api.products.unfavorite(productId);
            showMessage('info', '已取消收藏');
        } else {
            await api.products.favorite(productId);
            showMessage('success', '已收藏该商品');
        }

        // 刷新当前商品卡片状态
        const productCard = dom.productsView.querySelector(`.product-card[data-id="${productId}"]`);
        if (productCard) {
            const favoriteBtn = productCard.querySelector('.btn-favorite i');
            favoriteBtn.classList.toggle('text-red-500');
            favoriteBtn.classList.toggle('far');
            favoriteBtn.classList.toggle('fas');
        }
    } catch (error) {
        showMessage('error', error.message || '收藏操作失败');
    }
}

// 渲染分页
function renderPagination() {
    if (!dom.pageNumbers) return;

    const totalPages = Math.ceil(state.totalProducts / state.pageSize);
    dom.pageNumbers.innerHTML = '';

    if (totalPages <= 1) {
        dom.prevPageBtn.disabled = true;
        dom.nextPageBtn.disabled = true;
        return;
    }

    // 计算显示的页码范围（当前页前后各2页）
    let startPage = Math.max(1, state.currentPage - 2);
    let endPage = Math.min(totalPages, state.currentPage + 2);

    // 处理页码范围过窄的情况
    if (endPage - startPage < 4 && totalPages > 4) {
        if (state.currentPage <= 3) {
            startPage = 1;
            endPage = 5;
        } else if (state.currentPage >= totalPages - 2) {
            startPage = totalPages - 4;
            endPage = totalPages;
        }
    }

    // 添加页码按钮
    for (let i = startPage; i <= endPage; i++) {
        const pageBtn = document.createElement('button');
        pageBtn.className = `page-btn ${i === state.currentPage ? 'active' : ''}`;
        pageBtn.textContent = i;
        pageBtn.addEventListener('click', () => loadProducts(i));
        dom.pageNumbers.appendChild(pageBtn);
    }

    // 更新上一页/下一页按钮状态
    dom.prevPageBtn.disabled = state.currentPage === 1;
    dom.nextPageBtn.disabled = state.currentPage === totalPages;
}

// 更新搜索结果数量显示
function updateResultCount() {
    if (dom.resultCount) {
        dom.resultCount.textContent = `共 ${state.totalProducts} 件商品`;
    }
}

// 初始化筛选功能
function initFilters() {
    if (dom.categoryFilter) {
        dom.categoryFilter.addEventListener('change', handleFilterChange);
    }
    if (dom.sortBy) {
        dom.sortBy.addEventListener('change', handleFilterChange);
    }
    if (dom.minPrice && dom.maxPrice) {
        dom.minPrice.addEventListener('change', handleFilterChange);
        dom.maxPrice.addEventListener('change', handleFilterChange);
    }
}

// 处理筛选条件变化
function handleFilterChange() {
    const filters = {
        categoryId: dom.categoryFilter ? dom.categoryFilter.value : '',
        sortBy: dom.sortBy ? dom.sortBy.value : '',
        minPrice: dom.minPrice ? dom.minPrice.value : '',
        maxPrice: dom.maxPrice ? dom.maxPrice.value : ''
    };

    // 验证价格范围
    if (filters.minPrice && filters.maxPrice && parseFloat(filters.minPrice) > parseFloat(filters.maxPrice)) {
        showMessage('warning', '最低价格不能高于最高价格');
        return;
    }

    loadProducts(1, filters);
}

// 初始化视图切换功能
function initViewToggle() {
    if (!dom.viewBtns) return;

    dom.viewBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            dom.viewBtns.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            state.currentView = btn.dataset.view;

            // 添加视图切换动画
            const productCards = document.querySelectorAll('.product-card');
            productCards.forEach(card => {
                card.classList.add('opacity-0');
                setTimeout(() => {
                    card.classList.remove('list-view', 'grid-view');
                    card.classList.add(`${state.currentView}-view`);
                    card.classList.remove('opacity-0');
                }, 100);
            });
        });
    });
}

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', () => {
    loadProducts();
    initFilters();
    initViewToggle();

    // 从URL获取分类参数
    const urlParams = new URLSearchParams(window.location.search);
    const category = urlParams.get('category');
    if (category && dom.categoryFilter) {
        dom.categoryFilter.value = category;
        handleFilterChange();
    }

    // 监听购物车数量更新事件
    window.addEventListener('cartCountUpdated', updateCartBadge);
});

// 更新购物车徽章
function updateCartBadge() {
    // 这里可以添加获取购物车数量并更新徽章的逻辑
    console.log('更新购物车数量徽章');
}